import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:xvideos/assets_tool/images.dart';
import 'package:xvideos/hj_page/community_business/widget/post_user_info_view.dart';
import 'package:xvideos/hj_page/community_business/widget/post_word_rich_text.dart';
import 'package:xvideos/hj_page/mine_business/widgets/common_alert.dart';
import 'package:xvideos/hj_utils/date_time_util.dart';
import 'package:xvideos/hj_utils/widget_utils.dart';
import 'package:xvideos/tools_base/global_store/store.dart';
import 'package:xvideos/tools_base/widget/net_image_widget.dart';

import '../../../hj_model/video_model.dart';
import '../../find/rank_module/video_rank_cell.dart';
import '../../home_business/widget/collect_status_wrapper.dart';
import '../community_tag_page/community_tag_page.dart';
import '../post_detail_page/post_detail_page.dart';

typedef OnItemCheckCallback = void Function(VideoModel videoModel, bool isChecked);

class CommunityPostWidget extends StatefulWidget {
  final VideoModel videoModel;
  final List<VideoModel>? videoModels;
  final GestureTapCallback? clickCallback;
  final bool? showFollow;
  final bool isMyPublish; // 我的发布模式
  final bool isEditStatus; // 编辑模式
  final bool? showTags; // 是否展示标签
  final EdgeInsetsGeometry? padding;
  final bool? showLine; //展示分割线
  final bool showCheck; //展示勾选框
  final OnItemCheckCallback? onItemCheck;
  final bool isChecked; //是否选中
  final int? rankIndex; // 排行
  const CommunityPostWidget({
    Key? key,
    required this.videoModel,
    this.clickCallback,
    this.showFollow,
    this.isMyPublish = false,
    this.isEditStatus = false,
    this.videoModels,
    this.showTags = true,
    this.padding = const EdgeInsets.fromLTRB(16, 10, 16, 10),
    this.showLine = true,
    this.showCheck = false,
    this.onItemCheck,
    this.isChecked = false,
    this.rankIndex,
  });

  @override
  State<StatefulWidget> createState() => _CommunityPostWidgetState();
}

class _CommunityPostWidgetState extends State<CommunityPostWidget> {
  VideoModel? get videoModel => widget.videoModel;

  bool get isMe => GlobalStore().isMe(videoModel?.publisher?.uid);

  @override
  Widget build(BuildContext context) {
    if (videoModel?.sourceURL?.isNotEmpty == true) {
      videoModel?.seriesCover?.remove(videoModel?.cover ?? "");
    }
    return InkWell(
      onTap: widget.clickCallback ??
          () => Get.toNamed(
                PostDetailPage.routeName,
                arguments: PostDetailPageArgument(
                  id: videoModel?.id,
                  models: widget.videoModels,
                ),
              ),
      child: Container(
        color: Colors.white.withOpacity(.0),
        padding: widget.padding,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            /// 顶部样式
            if (!widget.isMyPublish)
              Container(
                padding: EdgeInsets.only(bottom: 12),
                child: Row(
                  children: [
                    Expanded(child:  PostUserInfoView(
                      model: widget.videoModel,
                      isEditStatus: widget.isEditStatus,
                    ),),
                    if(widget.rankIndex != null)
                      Row(
                        children: [
                          Image.asset(rankImgPath(widget.rankIndex!), width: 24),
                          SizedBox(width: 4),
                          Text(
                            "NO.${widget.rankIndex! + 1}",
                            style: TextStyle(
                              color: rankColor(widget.rankIndex!),
                              fontSize: 14,
                            ),
                          ),
                        ],
                      ),
                  ],
                ),
              )
            else ...[
              Row(
                children: [
                  Text(
                    '${_postStatusPrefix()}于${formatTimeTwo(widget.videoModel.createAtFix)}',
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: Color(0x59FFFFFF), fontSize: 14),
                  ),
                  Spacer(),
                  if (widget.showCheck)
                    GestureDetector(
                      onTap: () => widget.onItemCheck?.call(widget.videoModel, !widget.isChecked),
                      child: Stack(
                        alignment: Alignment.center,
                        children: [
                          Container(
                            width: 18,
                            height: 18,
                            decoration: BoxDecoration(
                              color: widget.isChecked ? Colors.white : Colors.transparent,
                              shape: BoxShape.circle,
                            ),
                          ),
                          Icon(
                            widget.isChecked ? CupertinoIcons.checkmark_circle_fill : CupertinoIcons.circle,
                            color: widget.isChecked ? Color(0xffE1351F) : Color(0xff999999),
                          ),
                        ],
                      ),
                    ),
                  if (showStatusDesc)
                    InkWell(
                      onTap: () async {
                        if (widget.videoModel.status == 2) {
                          await Get.dialog(
                            CommonAlert(
                              title: "未过审原因",
                              desc: '${widget.videoModel.reason}',
                              showLeftButton: false,
                              rightBtn: '我知道了',
                            ),
                          );
                        }
                      },
                      child: Text(
                        '${_postStatusDesc()}',
                        style: TextStyle(
                          color: _postStatusColor(),
                          fontSize: 14.sp,
                        ),
                      ),
                    ),
                ],
              ),
              14.sizeBoxH,
            ],

            if (widget.videoModel.title?.trim().isNotEmpty == true)
              Container(
                padding: EdgeInsets.only(bottom: 12),
                child: PostWordRichText(
                  videoModel: widget.videoModel,
                ),
              ),
            _buildCoverType(),
            12.sizeBoxH,
            Row(
              children: [
                _buildBottomItem(videoModel?.pageViewCount?.humanizeFormat, "count_eye_gray.png".communityPath),
                12.sizeBoxW,
                _buildBottomItem(videoModel?.commentCount?.humanizeFormat, "count_msg_gray.png".communityPath),
                12.sizeBoxW,
                CollectStatusWrapper(
                  videoModel: videoModel,
                  builder: () {
                    return _buildBottomItem(
                      videoModel?.likeCount?.humanizeFormat,
                      videoModel?.vidStatus?.hasLiked == true ? "like_red.png".communityPath : "like_empty_gray.png".communityPath,
                    );
                  },
                ),
                Spacer(),
                if (widget.showTags == true) _buildTagDesc(),
              ],
            ),
            if (widget.showLine == true) ...[
              10.sizeBoxH,
              Container(
                height: 1,
                margin: EdgeInsets.only(top: 10),
                color: Colors.white.withOpacity(.1),
              ),
            ],
          ],
        ),
      ),
    );
  }

  String _postStatusPrefix() {
    if (widget.videoModel.status == 1) {
      return '发布';
    } else {
      return '上传';
    }
  }

  bool get showStatusDesc => widget.videoModel.status != 1 && widget.showCheck == false;

  String _postStatusDesc() {
    switch (widget.videoModel.status) {
      case 0:
        return '待审核';
      case 1:
        return '已成功';
      case 2:
        return '未通过原因';
      case 5:
      default:
        return '未知状态';
    }
  }

  Color _postStatusColor() {
    if (widget.videoModel.status == 2) return Color(0xffFD0563);
    return Color(0xff3476FF);
  }

  /// 视频帖子内容
  Widget _buildCoverType() {
    if ((videoModel?.seriesCover?.length ?? 0) == 0 && videoModel?.sourceURL?.isNotEmpty == true) {
      //只有一张显示视频封面
      return Container(
        height: 204,
        child: Stack(
          fit: StackFit.expand,
          children: [
            NetworkImageLoader(
              imageUrl: videoModel?.cover ?? '',
              borderRadius: 6,
            ),
            Container(
              alignment: Alignment.center,
              child: Image.asset(
                "play_icon.png".communityPath,
                width: 32,
                height: 32,
              ),
            ),
            Positioned(
              child: _buildPermission(),
              right: 0,
              top: 0,
            ),
          ],
        ),
      );
    } else {
      int coverCount = videoModel?.seriesCover?.length ?? 0;
      if (videoModel?.sourceURL?.isNotEmpty == true) {
        coverCount++;
      }
      return GridView.builder(
        padding: EdgeInsets.zero,
        physics: const NeverScrollableScrollPhysics(),
        itemCount: min(3, coverCount),
        shrinkWrap: true,
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          mainAxisSpacing: 6,
          crossAxisSpacing: 6,
          childAspectRatio: 1,
        ),
        itemBuilder: (context, index) {
          bool isLast = index == 2 || coverCount == index + 1;
          String imgPath = "";
          if (isLast && videoModel?.sourceURL?.isNotEmpty == true) {
            imgPath = videoModel?.cover ?? "";
          } else if (index < (videoModel?.seriesCover?.length ?? 0)) {
            imgPath = videoModel!.seriesCover![index];
          } else {
            imgPath = videoModel?.cover ?? "";
          }
          return Stack(
            fit: StackFit.expand,
            children: [
              NetworkImageLoader(
                imageUrl: imgPath,
                borderRadius: 6,
              ),
              if (isLast)
                Positioned(
                  child: _buildPermission(),
                  right: 0,
                  top: 0,
                ),
              if (isLast && videoModel?.sourceURL?.isNotEmpty == true)
                Container(
                  alignment: Alignment.center,
                  child: Image.asset(
                    "play_icon.png".communityPath,
                    width: 30,
                    height: 30,
                  ),
                )
              else if (isLast && coverCount > 3)
                Positioned(
                  bottom: 6,
                  right: 6,
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 6, vertical: 1),
                    decoration: BoxDecoration(
                      color: Colors.black.withOpacity(0.6),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Text(
                      "+${coverCount - 3}",
                      style: TextStyle(
                        fontSize: 12,
                        color: Color(0xffF1F1F1),
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                )
              else
                SizedBox(),
            ],
          );
        },
      );
    }
  }

  Widget _buildPermission() {
    if (widget.videoModel.permission != 1) return SizedBox.shrink();
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 6, vertical: 3),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.only(
          topRight: Radius.circular(6),
          bottomLeft: Radius.circular(6),
        ),
        gradient: LinearGradient(
          colors: [
            Color(0xffDB361F),
            Color(0xffDB361F),
          ],
        ),
      ),
      child: Image.asset("coin.webp".commonImgPath, width: 14, height: 14),
    );
  }

  Widget _buildBottomItem(String? title, String imagePath) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Image.asset(imagePath, width: 20, height: 20),
        const SizedBox(width: 2),
        Text(
          title ?? "",
          style: TextStyle(
            color: Color(0xff999999),
            fontSize: 12,
          ),
        ),
      ],
    );
  }

  /// 帖子标签
  Widget _buildTagDesc() {
    if (widget.videoModel.tags?.isNotEmpty != true) return SizedBox();
    TagsBean tagsBean = widget.videoModel.tags!.first;
    tagsBean.newsType = widget.videoModel.newsType;
    return GestureDetector(
      onTap: () => Get.toNamed(CommunityTagDetailPage.routeName, arguments: tagsBean),
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(3),
          color: Color(0x0DFFFFFF),
        ),
        child: Text(
          '#${tagsBean.name ?? ''}',
          style: TextStyle(
            color: Color(0x73FFFFFF),
            fontSize: 12,
          ),
        ),
      ),
    );
  }
}
